package leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Project : algorithm-learning-java
 * @Package : leetcode
 * @Author : Ruoyu Wang
 * @User : Momenta
 * @DateTime : 2024/1/10 14:28
 */
public class Q0039 {
    List<List<Integer>> res = new ArrayList<>();
    List<Integer> tmp = new ArrayList<>();
    int[] candidates;
    int target;

    private void dfs(int k, int sum) {
        if (sum == target) {
            res.add(new ArrayList<>(tmp));
            return;
        }
        for (int i = k; i < candidates.length; i++) {
            if (candidates[i] > target - sum) return;
            tmp.add(candidates[i]);
            dfs(i, sum + candidates[i]);
            tmp.remove(tmp.size() - 1);
        }
    }

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);
        this.candidates = candidates;
        this.target = target;
        dfs(0, 0);
        return res;
    }

    public static void main(String[] args) {
        Q0039 sl = new Q0039();
        int[] candidates = {8, 7, 4, 3};
        int target = 11;
        System.out.println(sl.combinationSum(candidates, target));
    }
}
